package com.web44.springboot.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * @Title: ErrorInterceptor
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/3/1 14:06
 */
@Component
public class ErrorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          if( !(handler instanceof HandlerMethod)) {
              return true;
          }

        HandlerMethod hm = (HandlerMethod)handler;
          // 获取方法
        Method method = hm.getMethod();
        // 判断方法上的注解是否包含 ResponseBody
        boolean flag01 = method.isAnnotationPresent(ResponseBody.class);
        // 判断类上的注解是否包含  RestController
        boolean flag02 = hm.getBeanType().isAnnotationPresent(RestController.class);
        // 判断是否是resultfull风格
        boolean isJson = flag01 || flag02;
        request.setAttribute("isJson",isJson);
        return true;


    }
}
